package com.applcn.message.utils.sms;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.applcn.core.base.Result;
import com.applcn.message.apollo.SmsConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 短信开关类
 */
@Component
@RequiredArgsConstructor
public class SmsUtil {

    private static Map<Integer, AbstractSmsUtil> registerService = new ConcurrentHashMap<>(128);

    private final List<AbstractSmsUtil> abstractSmsUtils;
    private final SmsConfig smsConfig;

    @PostConstruct
    private void init() {
        abstractSmsUtils.forEach((s) -> {
            registerService.put(s.getCode(), s);
        });
    }

    private AbstractSmsUtil getSmsUtil(int code) {
        AbstractSmsUtil abstractSMSUtil = registerService.get(code);
        Assert.notNull(abstractSMSUtil, "未接入平台短信业务");
        return abstractSMSUtil;
    }

    /**
     * 发送短信验证码
     *
     * @param phone
     * @param smsSign
     * @param templateId
     * @param code
     * @param expire
     */
    public Result sendMessage(String phone, String smsSign, String templateId, String code, String expire) {
        if (StrUtil.isBlank(expire)) {
            expire = smsConfig.getExpire();
        }
        return getSmsUtil(smsConfig.getChoice()).sendSmsMessage(phone, smsSign, templateId, code, expire);
    }

    /**
     * 群发短信
     *
     * @param phones
     * @param smsSign
     * @param templateId
     * @param params
     * @return
     */
    public Result sendMessageGroup(String[] phones, String smsSign, String templateId, String[] params) {
        return getSmsUtil(smsConfig.getChoice()).sendMessageGroup(phones, smsSign, templateId, params);
    }

}
